<!-- 收款合同申请及变更流程 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="htbh" :required="checkRequired('htbh')">
          <u--input v-model="model.htbh" disabled placeholder="请输入单据编号"></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" :required="checkRequired('propose')">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" :required="checkRequired('proposerDeptId')">
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
				<u-form-item label="申请时间" prop="createTime" :required="checkRequired('createTime')">
				  <u--input v-model="model.createTime" disabled placeholder="请选择申请时间"></u--input>
				</u-form-item>
				<view v-if="model.lx == '2'">
					<u-form-item label="合同编号" prop="caId" :required="checkRequired('caId')">
						<h-select-contract-manager-input
							v-model="model.caId"
							:disabled="checkDisabled('caId')"
							objectField="model.caId"
							placeholder="请选择合同编号"
							:allList="true"
							:status="'2,3,7'"
							:muitFlag="true"
							:changeStatus="'unchanged'"
							style="width: 100%;"
							htlx="1"
							:triggerChange="true"
							@input="htbhChange"
						>
						</h-select-contract-manager-input>
					</u-form-item>
				</view>
        <u-form-item label="合同名称" prop="htmc" :required="checkRequired('htmc')">
          <u--input v-model="model.htmc" :disabled="checkDisabled('htmc')" placeholder="请输入合同名称"></u--input>
        </u-form-item>
				<u-form-item label="合同类型" prop="htlx" required>
					<h-select-input-tag
						style="width: 100%;"
						v-model="model.htlx"
						disabled
						placeholder="请选择合同类型"
						dictName="htlx_type"
					></h-select-input-tag>
				</u-form-item>
				<view v-if="model.lx == '2'">
					<u-form-item label="变更类型" prop="bglx" :required="checkRequired('bglx')">
						<h-select-input-tag
							style="width: 100%;"
							v-model="model.bglx"
							:disabled="checkDisabled('bglx')"
							placeholder="请选择变更类型"
							dictName="bglx_type"
						></h-select-input-tag>
					</u-form-item>
					<view v-if="model.bglx == '2'">
						<u-form-item label="终止时间" prop="stopTime" :required="checkRequired('stopTime')">
							<h-time-select
							  mode="date"
								:disabled="checkDisabled('stopTime')"
							  v-model="model.stopTime"
							  placeholder="请选择终止时间"
							></h-time-select>
						</u-form-item>
					</view>
				</view>
        <u-form-item label="项目名称" prop="xmmc" :required="checkRequired('xmmc')">
					<h-select-project-input
						ref="projectSelect"
						:disabled="model.lx == '2' || checkDisabled('xmmc')"
						isOldSystem="!1"
						currentProjectStatus="!2"
						v-model="model.xmmc"
						style="width: 100%"
						placeholder="请选择项目名称"
						objectField="model.xmmc"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@input="xmmcInput"
						:proDisabled="true"
						:projectStatus="'2'"
					></h-select-project-input>
        </u-form-item>
        <u-form-item label="经营团队" prop="jytd" :required="checkRequired('jytd')">
					<h-select-team-input
						@input="changeBusinessCompany"
						:disabled="checkDisabled('jytd')"
						style="width: 100%;"
						v-model="model.jytd"
						objectField="model.jytd"
						placeholder="请选择经营团队"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						:tdlx="1"
					></h-select-team-input>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="yjgsnd" :required="checkRequired('yjgsnd')">
					<h-dict-select
						style="width: 100%" 
						v-model="model.yjgsnd" 
						placeholder="请选择业绩归属年度" 
						:disabled="checkDisabled('yjgsnd')"
						dictName="yjgsnd"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
        </u-form-item>
        <u-form-item label="签订单位" prop="qddw" :required="checkRequired('qddw')">
          <h-select-company-input
            style="width: 100%"
						:disabled="checkDisabled('qddw')"
            v-model="model.qddw"
            border="surround"
            placeholder="请选择签订单位"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@input="handleChangeFrameContract"
            objectField="model.qddw"
          ></h-select-company-input>
        </u-form-item>
				<u-form-item label="框架下合同" prop="isFrameContract" :required="checkRequired('isFrameContract')">
					<h-dict-radio
						v-model="model.isFrameContract" 
						:disabled="checkDisabled('isFrameContract')"
						placeholder="请选择框架下合同" 
						dictName="is_frame_contract"
						@input="handleChangeFrameContract"
					></h-dict-radio>
				</u-form-item>
				<view v-if="showframeContract">
					<u-form-item label="关联框架合同" prop="frameContractId" :required="checkRequired('frameContractId')">
						<h-select-contract-manager-input
							:disabled="!model.qddw || checkDisabled('frameContractId')"
							v-model="model.frameContractId"
							objectField="model.frameContractId"
							placeholder="请选择关联框架合同"
							:allList="true"
							:status="'2,3,7'"
							:muitFlag="true"
							changeStatus="unchanged"
							contractType="frameworkContract"
							htlx="3"
							:signUnit="model.qddw"
							navigationBarTitle="选择框架合同"
							:triggerChange="true" >
						</h-select-contract-manager-input>
					</u-form-item>
				</view>
        <u-form-item label="项目承接人" prop="xmcjr" :required="checkRequired('xmcjr')">
          <h-select-person-input-popup
            v-model="model.xmcjr"
						:disabled="checkDisabled('xmcjr')"
            style="width: 100%;"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="业主单位" prop="yzdw" :required="checkRequired('yzdw')">
          <h-select-customer-input
            style="width: 100%"
            v-model="model.yzdw"
						:disabled="checkDisabled('yzdw')"
            objectField="model.yzdw"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@input="yzdwChange"
          ></h-select-customer-input>
        </u-form-item>
        <u-form-item label="联系人" prop="lxr">
          <h-select-input-tag
            style="width: 100%;"
            v-model="model.lxr"
						:disabled="checkDisabled('lxr')"
            objectField="model.lxr"
            placeholder="请选择联系人"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :dictName="cust_lxr"
						errorMessage="请选择业主单位"
            @change="lxrChange"
          ></h-select-input-tag>
        </u-form-item>
				<u-form-item label="联系方式" prop="lxfs">
				  <u--input  placeholder="请输入联系方式" :disabled="checkDisabled('lxfs')" v-model="model.lxfs"></u--input>
				</u-form-item>
				<u-form-item label="业主角色" prop="ownerRole" :required="checkRequired('ownerRole')">
					<h-dict-select
						style="width: 100%" 
						v-model="model.ownerRole"
						:disabled="checkDisabled('ownerRole')"
						placeholder="请选择业主角色" 
						dictName="owner_role">
					</h-dict-select>
				</u-form-item>
				<u-form-item label="企业类型" prop="enterpriseType" :required="checkRequired('enterpriseType')">
					<h-dict-select
						disabled
						style="width: 100%" 
						v-model="model.enterpriseType"
						placeholder="请选择企业类型" 
						dictName="enterprise_type">
					</h-dict-select>
				</u-form-item>
				<u-form-item label="签订日期" prop="qdrq" :required="checkRequired('qdrq')">
          <h-time-select
            :disabled="checkDisabled('qdrq')"
            mode="date"
            ref="remittanceDate"
            v-model="model.qdrq"
            placeholder="请选择签订日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
				<u-form-item label="服务期限开始日期" prop="fwqx" :required="checkRequired('fwqx')">
				  <h-time-select
				    mode="date"
				    ref="remittanceDate"
				    v-model="model.fwqx"
						:disabled="checkDisabled('fwqx')"
				    placeholder="请选择服务期限开始日期"
				    border="surround"
				    suffixIcon="calendar-fill"
				    :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="handleBorrowDateChange"
				  ></h-time-select>
				</u-form-item>
				<u-form-item label="服务期限结束日期" prop="fwqxEnd" :required="checkRequired('fwqxEnd')">
				  <h-time-select
				    mode="date"
				    ref="remittanceDate"
				    v-model="model.fwqxEnd"
						:disabled="checkDisabled('fwqxEnd')"
				    placeholder="请选择服务期限结束日期"
				    border="surround"
				    suffixIcon="calendar-fill"
				    :suffixIconStyle="{ color: '#B2B2B2' }"
						:minDate="model.fwqx?(new Date(model.fwqx)).getTime():315504000000"
						@change="predictReturnDateChange"
				  ></h-time-select>
				</u-form-item>
				<u-form-item label="是否存档" prop="sfcd" :required="checkRequired('sfcd')">
				  <h-select-input-tag
						:disabled="checkDisabled('sfcd')"
				    class="w-100"
				    v-model="model.sfcd"
				    objectField="model.sfcd"
				    placeholder="请选择是否存档"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    border="surround"
				    dictName="yn"
						@change="handleRules2"
				  ></h-select-input-tag>
				</u-form-item>
				<view v-if="model.sfcd === '1'">
				  <u-form-item label="合同存档份数" prop="cdfs" :required="checkRequired('cdfs')">
				    <h-number-input
							placeholder="请输入合同存档份数"
							:disabled="checkDisabled('cdfs')"
							v-model="model.cdfs"
							:digit="0"
						:min="0"></h-number-input>
				  </u-form-item>
					<u-form-item label="存档形式" prop="contractFileType" :required="checkRequired('contractFileType')">
				    <h-dict-select
				    	style="width: 100%"
							:disabled="checkDisabled('contractFileType')"
				    	v-model="model.contractFileType"
				    	placeholder="请选择存档形式" 
				    	dictName="contract_file_type">
				    </h-dict-select>
				  </u-form-item>
				</view>
      </view>
      <view class="basic-style">
        <view class="basic-title basic-border">委托方(合同甲方)信息</view>
        <view class="space-y-1 py-1" v-if="!checkDisabled('entrustList')">
          <u-button size="small" type="primary" @click="addFormA">新增</u-button>
        </view>
        <view v-for="(item, index) in formDataA" :key="index">
				<FormAInfo
					:disabled="checkDisabled('entrustList')"
					:item="item"
					:index="index"
					:signSealWay="model.signSealWay"
					@edit="handleEditFormA"
					@remove="handleRemoveFormA"
					@copy="handleCopyFormA" />
        </view>
        <u-popup mode="bottom" :show="showFormModalA">
          <FormA ref="dataFormA" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitA" @close="closeFormModalA" />
        </u-popup>
      </view>
      <view class="basic-style">
        <view class="basic-title basic-border pt-1">受托方(合同乙方)信息</view>
        <view class="space-y-1 py-1" v-if="!checkDisabled('trusteeList')">
          <u-button size="small" type="primary" @click="addFormB">新增</u-button>
        </view>
        <view v-for="(item, index) in formDataB" :key="index">
					<FormBInfo
						:item="item"
						:disabled="checkDisabled('trusteeList')"
						:index="index"
						:signSealWay="model.signSealWay"
						@edit="handleEditFormB"
						@remove="handleRemoveFormB"
						@copy="handleCopyFormB" />
        </view>
        <u-popup mode="bottom" :show="showFormModalB">
          <FormB ref="dataFormB" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitB" @close="closeFormModalB" />
        </u-popup>
      </view>
			<view class="basic-style">
        <view class="basic-title basic-border pt-1">合同金额</view>
				<u-form-item label="本次合同额(元)" prop="bchte" :required="checkRequired('bchte')">
					<h-money-input placeholder="请输入本次合同额" :disabled="checkDisabled('bchte')" v-model="model.bchte" @change="convertMoney2"></h-money-input>
				</u-form-item>
				<u-form-item label="本次合同额大写" prop="bchtedx">
				  <u--input disabled placeholder="请输入本次合同额大写" v-model="model.bchtedx"></u--input>
				</u-form-item>
				<u-form-item
					label="经营绩效(元)"
					prop="businessPerformance"
					:borderBottom="false"
					ref="item1"
					:required="checkRequired('businessPerformance')">
					<h-money-input
						type="number"
						placeholder="请输入经营绩效"
						v-model="model.businessPerformance"
						:disabled="checkDisabled('businessPerformance')"
					></h-money-input>
				</u-form-item>
			</view>
      <view class="basic-style">
        <view class="basic-title basic-border">收付款计划</view>
				<u-form-item label="是否变更款项信息" prop="sfbgkxxx" :required="checkRequired('sfbgkxxx')" v-if="model.lx == '2'">
					<h-dict-radio v-model="model.sfbgkxxx" dictName="yn" :disabled="checkDisabled('sfbgkxxx')"></h-dict-radio>
				</u-form-item>
        <view class="space-y-1 py-1" v-if="!checkDisabled('planList')">
          <u-button size="small" type="primary" @click="addFormC">新增</u-button>
        </view>
        <view v-for="(item, index) in formDataC" :key="index">
        	<FormCInfo 
        		:item="item"
						:showKxxx="showKxxx"
        		:index="index"
        		@edit="handleEditFormC"
        		@detail="handleDetailFormC"
        		@remove="handleRemoveFormC"
        		@copy="handleCopyFormC"
        		:disabled="checkDisabled('planList')"
        	/>
        </view>
        <u-popup mode="bottom" :show="showFormModalC" :closeOnClickOverlay="false">
          <FormC
						ref="dataFormC"
						:dataSource="formDataC"
						:index="index"
						:htlx="model.htlx"
						:projectId="model.xmmc"
						:disabled="checkDisabled('planList')"
						@submit="handleFormSubmitC"
						@close="closeFormModalC" />
        </u-popup>
      </view>
			<view class="basic-style">
			  <view class="basic-title basic-border pt-1">任务信息</view>
				<u-form-item label="分配方式" prop="distributionMethod" :required="checkRequired('distributionMethod')">
				  <h-select-input-tag
						style="width: 100%;"
				    v-model="model.distributionMethod"
						:disabled="checkDisabled('distributionMethod')"
				    placeholder="请选择是分配方式"
						@change="changeMoney"
				    dictName="distribution_method"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item label="主生产团队" prop="mainProductionTeam">
					<h-select-team-input
						style="width: 100%;"
						v-model="model.mainProductionTeam"
						disabled
						objectField="model.mainProductionTeam"
						placeholder="请选择主生产团队"
						:tdlx="2"
						:triggerChange="true"
					></h-select-team-input>
				</u-form-item>
			  <TaskInfo
					:entities="dataSource2"
					:bchte="model.bchte"
					:newDisabled="checkDisabled('classList')"
					:distributionMethod="model.distributionMethod"/>
			</view>
			<view class="basic-style">
        <view class="basic-title basic-border">用印信息</view>
				<u-form-item label="是否用印" prop="sfyz" :required="checkRequired('sfyz')">
				  <h-select-input-tag
				    style="width: 100%;"
				    v-model="model.sfyz"
						:disabled="checkDisabled('sfyz')"
				    objectField="model.sfyz"
				    placeholder="请选择是否用印"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    border="surround"
				    dictName="yn"
						@change="handleRules"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item v-if="model.sfyz == '0'" label="无正式合同" prop="noFormalContract" :required="checkRequired('noFormalContract')">
					<h-dict-radio :disabled="checkDisabled('noFormalContract')" v-model="model.noFormalContract" dictName="YES_OR_NO"></h-dict-radio>
				</u-form-item>
				<view v-if="model.sfyz === '1'">
					<u-form-item label="用印类型" prop="signSealWay" :required="checkRequired('signSealWay')">
					  <h-select-input-tag
					    class="w-100"
					    v-model="model.signSealWay"
							:disabled="checkDisabled('signSealWay')"
					    objectField="model.signSealWay"
					    placeholder="请选择用印类型"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
					    border="surround"
					    dictName="seal_way"
							@change="handleSignSealWay"
					  ></h-select-input-tag>
					</u-form-item>
				  <u-form-item label="印章类型" prop="yzlx" :required="checkRequired('yzlx')">
						<h-dict-multi-select
							v-model="model.yzlx"
							:disabled="checkDisabled('yzlx')"
							style="width: 100%" 
							placeholder="请选择印章类型"
							dictName="yzlx_type"
							border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{color: '#B2B2B2'}"
						></h-dict-multi-select>
				  </u-form-item>
				  <u-form-item label="用印份数" prop="yyfs" :required="checkRequired('yyfs')">
						<h-number-input placeholder="请输入用印份数" v-model="model.yyfs" :disabled="checkDisabled('yyfs')" :digit="0" :min="1"></h-number-input>
				  </u-form-item>
				</view>
				  <u-form-item prop="signFile" :required="checkRequired('signFile')" v-if="model.sfyz == 1">
						<view slot="label" style="position: relative;">
							<view
								style="position: absolute;
									left: -9px;
									color: #f56c6c;
									font-size: 20px;
									top: 3px;
								}">*</view>
								<view
									style="justify-content: flex-start;
									font-size: 14px;
									color: rgb(178, 178, 178);">
									用印文件<span style="color: #faad14;font-weight: 600; font-size: 12px;">（请上传只需盖章的用印文件！）</span>
								</view>
						</view>
						<view class="py-1 space-y-1" style="width: 100%">
							<view style="color: red" v-if="!checkDisabled('signFile')">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
							<h-upload-file v-model="model.signFile" :fillSize="50" :disabled="checkDisabled('signFile')" :isIcon="false" :isSingle="true" fileType=".pdf, .PDF, .doc, .docx" fileTypeText="请上传word与pdf格式的文件！"></h-upload-file>
							<file-list v-if="model.signFile" v-model="model.signFile" :isDelete="!checkDisabled('signFile')"></file-list>
						</view>
					</u-form-item>
				<!-- </view> -->
				<view v-if="!model.sfyz||model.sfyz=='0'">
					<u-form-item label="合同原件" prop="masterCopy" :required="checkRequired('masterCopy')">
						<view class="space-y-1" style="width: 100%;">
						  <view
								style="color: red"
								v-if="!checkDisabled('masterCopy')">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
						  <h-upload-file v-model="model.masterCopy" :isIcon="false" :disabled="checkDisabled('masterCopy')"></h-upload-file>
						  <file-list v-if="model.masterCopy" v-model="model.masterCopy" :isDelete="!checkDisabled('masterCopy')"></file-list>
						</view>
					</u-form-item>
				</view>
			</view>

      <view class="basic-style">
        <u-form-item label="备注" prop="bz">
					<!-- #ifdef APP -->
					<u--textarea :confirm-type="null" count v-model="model.bz" :disabled="checkDisabled('bz')" placeholder="请输入备注" maxlength="500"></u--textarea>
					<!-- #endif -->
          <!-- #ifdef H5 -->
          <u--textarea confirm-type="done" v-model="model.bz" :disabled="checkDisabled('bz')" placeholder="请输入备注" maxlength="500"></u--textarea>
          <!-- #endif -->
        </u-form-item>
        <u-form-item label="邮寄信息" prop="yjxx">
          <!-- #ifdef APP || APP-PLUS -->
          <u--textarea :confirm-type="null" count v-model="model.yjxx" :disabled="checkDisabled('yjxx')" placeholder="请输入邮寄信息" maxlength="500"></u--textarea>
          <!-- #endif -->
					<!-- #ifdef H5 -->
					<u--textarea confirm-type="done" v-model="model.yjxx" :disabled="checkDisabled('yjxx')" placeholder="请输入邮寄信息" maxlength="500"></u--textarea>
					<!-- #endif -->
        </u-form-item>
				<u-form-item label="变更说明" prop="contractChangeReason" v-if="model.lx == '2'" :required="checkRequired('contractChangeReason')">
				  <!-- #ifdef APP || APP-PLUS -->
				  <u--textarea :confirm-type="null" count v-model="model.contractChangeReason" :disabled="checkDisabled('contractChangeReason')" placeholder="请输入变更说明" maxlength="500"></u--textarea>
				  <!-- #endif -->
					<!-- #ifdef H5 -->
					<u--textarea confirm-type="done" v-model="model.contractChangeReason" :disabled="checkDisabled('contractChangeReason')" placeholder="请输入变更说明" maxlength="500"></u--textarea>
					<!-- #endif -->
				</u-form-item>
      </view>
      <view class="basic-style">
        <view class="basic-title basic-border">相关附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red" v-if="!checkDisabled('xgfj')">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.xgfj" :isIcon="false" :disabled="checkDisabled('xgfj')"></h-upload-file>
          <file-list v-if="model.xgfj" v-model="model.xgfj" :isDelete="!checkDisabled('xgfj')"></file-list>
        </view>
      </view>
			<view class="basic-style">
			  <view class="basic-title basic-border">合同税率</view>
			  <view v-for="(item, index) in formDataRate" :key="index">
			  	<FormRateInfo 
			  		:item="item"
			  		:index="index"
			  		@edit="handleEditFormRate"
			  		@remove="handleRemoveFormRate"
			  		@copy="handleCopyFormRate"
			  		:disabled="checkDisabled('rateList')"
			  	/>
			  </view>
			  <u-popup mode="bottom" :show="showFormModalRate" :closeOnClickOverlay="false">
			    <FormRate
						ref="dataFormRate"
						:index="index"
						@submit="handleFormSubmitRate"
						@close="closeFormModalRate" />
			  </u-popup>
			</view>
			<view class="basic-style">
			  <u-form-item label="收入确认方式" prop="confirmIncomeMethod" :required="checkRequired('confirmIncomeMethod')">
			  	<h-dict-select
			  		:disabled="checkDisabled('confirmIncomeMethod')"
			  		style="width: 100%" 
			  		v-model="model.confirmIncomeMethod" 
			  		placeholder="请选择收入确认方式" 
			  		dictName="confirm_income_method">
			  	</h-dict-select>
			  </u-form-item>
			</view>
			
			<view class="space-x-1 px-1 btn_position">
				<backButton  @onSubmit="onSubmit" :nodeObj="nodeObj" :model="processModel" :resultObj="resultObj"></backButton>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
	<u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info, edit,checkContractById } from '@/api/finance/ErpFinanceInvoiceApplicationBillForm'
import { convertCurrency } from '@/utils/utils'
import {
  addInvoiceHandleRecordList,
  erpOmcProjectId,
  relationTaskList,
  erpFinanceProjectDepositBillqueryByEntity,
  querySupplierByIdserpOmcProjectId,
  erpOmcCustomerManagerContactId,
	erpOmcContractManagerClassListAll, // 任务信息
	erpOmcContractManagerEntrustListAll, // 委托方
	erpOmcContractManagerTrusteeListAll, // 受托方
	erpOmcContractManagerPlanListAll, // 收付款计划
	getProcessTaskTransInfo,// 流程审批
	erpOmcContractManagerTrusteeFinalList,
	erpOmcContractManagerEntrustFinalList,
	erpOmcContractManagerFinalQueryById,
	erpOmcContractManagerPlanFinalList,
	listContractFinalTaskByProjectId
} from '@/api/index'
import http from '@/utils/request/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import PrincipalForm from '@/pages/contract/components/PrincipalForm.vue'
import PrincipalFormInfo from '@/pages/contract/components/PrincipalFormInfo.vue'
import FormA from '@/pages/contract/components/FormA.vue'
import FormAInfo from '@/pages/contract/components/FormAInfo.vue'
import FormB from '@/pages/contract/components/FormB.vue'
import FormBInfo from '@/pages/contract/components/FormBInfo.vue'
import FormC from '@/pages/contract/components/FormC.vue'
import FormCInfo from '@/pages/contract/components/FormCInfo.vue'
import FormRate from '@/pages/contract/components/FormRate.vue' // 税率表单
import FormRateInfo from '@/pages/contract/components/FormRateInfo.vue' // 税率列表
import TaskInfo from '@/pages/contract/components/TaskInfo.vue'
import backButton from '@/components/backButton.vue'
import Decimal from "decimal.js"
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'

export default {
  name: 'ErpFinanceInvoiceApplicationBillForm',
  components: { backButton, fileList, PrincipalForm, PrincipalFormInfo, FormA, FormAInfo, FormB, FormBInfo, FormC, FormCInfo, FormRate, FormRateInfo,  TaskInfo },
  data() {
    return {
			/* 流程编辑审批字段 */
		processModel: {},
		extendUrlParams: {},
		tabvalue: {},
		nodeObj: {},
		dataNodeObj: '',
		resultObj: {}, // 流程图流转信息
		/* 流程编辑审批字段 */
		flag: false,
		cust_lxr: '',
		backUpApplicant: '',
		backUpTeamId: '',
		isReset: false,
		dictOptions: {},
		resetKey: '',
		index: null,
		isSubmit: false,
		id: '',
		dataSource2: [],
		basicFormA: {},
		basicFormB: {},
		basicFormC: {},
		basicFormRate: {}, // 税率表单
		showFormModalA: false,
		showFormModalB: false,
		showFormModalC: false,
		showFormModalRate: false, // 税率表单显隐
		// formDataA: [{ khdaId: '1598142020751310849', isFk: '1' }],
		formDataA: [],
		formDataB: [],
		formDataC: [],
		formDataRate: [], // 税率列表
		contractType: 1, // 代表项目收款合同， 2 代表项目付款合同
		model: {
			// 基本信息 - 公用
			bpmBizTitle: '',
			lx: 1, // 项目收款合同申请
			htbh: '', // 合同编号
			businessCompanyId: '', // 经营公司
			createTime: '', // 申请时间
			proposer: '', // 申请人
			proposerDeptId: '', // 申请部门
			htmc: '', // 合同名称
			xmmc: '', // 项目名称
			jytd: '', // 经营团队
			yjgsnd: '', // 业绩归属年度
			qddw: '', // 签订单位
			isFrameContract: '', // 框架下合同
			frameContractId: '', // 关联框架合同
			ownerRole: '', // 业主角色
			enterpriseType: '', // 企业类型
			mainProductionTeam: '', // 主生产团队
			xmcjr: '', // 项目承接人
			yzdw: '', // 业主单位
			lxr: '', // 联系人
			lxfs: '', // 联系方式
			qdrq: '', // 签订单位
			sfyz: '', //是否用印
			signSealWay: '', // 用印类型
			sfcd: '', // 是否存档
			cdfs: null, // 存档份数
			contractFileType: null, // 存档形式
			distributionMethod: '',// 分配方式
			htlx: 1,
			// 基本信息 - 非公用
			masterCopy: null,
			bchte: '',
			businessPerformance: '', // 经营绩效
			// 附件
			xgfj: null,
			signFile: null, // 用印文件
			contractChangeReason: '' // 变更说明
		},
      rules: {
				htbh: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        bchte: [{ required: true, message: '请输入本次合同额!' }],
        businessPerformance: [{ required: true, message: '请输入经营绩效!' }],
        fwqx: [{ required: true, message: '请选择服务期限开始日期!' }],
        fwqxEnd: [{ required: true, message: '请选择服务期限结束日期!' }],
        htlx: [{ required: true, message: '请选择合同类型!' }],
        htmc: [{ required: true, message: '请输入合同名称!' }],
        xmmc: [{ required: true, message: '请选择项目名称!' }],
        jytd: [{ required: true, message: '请选择经营团队!' }],
        yjgsnd: [{ required: true, message: '请选择业绩归属年度!' }],
        qddw: [{ required: true, message: '请选择签订单位!' }],
        isFrameContract: [{ required: true, message: '请选择框架下合同!' }],
        frameContractId: [{ required: true, message: '请选择关联框架合同!' }],
        ownerRole: [{ required: true, message: '请选择业主角色!' }],
        xmcjr: [{ required: true, message: '请选择项目承接人!' }],
        yzdw: [{ required: true, message: '请选择业主单位!' }],
        // yzlx: [{ required: true, message: '请选择印章类型!' }],
        // yyfs: [
        //   { required: true, message: '请填写用印份数!', trigger: 'blur' },
        //   { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
        // ],
        lxfs: [
          { required: false },
          { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!',trigger: ['blur','change'] },
        ],
        // masterCopy: [{ required: true, message: '请上传合同原件!' }],
        sfyz: [{ required: true, message: '请选择是否用印!' }],
        noFormalContract: [{ required: true, message: '请选择无正式合同!' }],
				signSealWay: [{ required: true, message: '请选择用印类型!' }],
				signFile: [{ required: true, message: '请上传用印文件!' }],
        distributionMethod: [{ required: true, message: '请选择分配方式!' }],
				contractChangeReason: [{ required: true, message: '请输入变更说明!' }],
        // sfcd: [{ required: true, message: '请选择是否存档!' }], // 升级版迭代1发起人禁用
      },
			// 代码生成后需手动设置流程编码
			flowCode: 'dev_erp_omc_contract_manager_001',
			formUrl: 'erp/omc/contractmanager/modules/ErpOmcContractManagerForm',
			formUrlMobile: '/pages/synergy/erpOmcContractManagerList',
			beanName: 'erpOmcContractManagerServiceImpl',
			processId: '1557651427069722625',
			projectName: '',
    }
  },
	async onLoad(options) {
		this.processModel = JSON.parse(decodeURIComponent(options.item))
		this.extendUrlParams = JSON.parse(decodeURIComponent(options.params))
		var that = this
		var eventChannel = ''
		// #ifdef APP-NVUE
		eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
		// #endif
		// #ifndef APP-NVUE
		eventChannel = this.getOpenerEventChannel()
		// #endif
		// 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
		eventChannel.on('sendMessage', function (data) {
		  that.tabvalue = data.tabvalue
		  that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
		  that.dataNodeObj = data.nodeObj
		  that.id = that.nodeObj.dataId
		  that.loadData(that.nodeObj.dataId)
			that.getProcessTaskTrans(that.processModel.id)
		})
		this.initRules()
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formDataA.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
		sfbg () {
			if (this.model.lx  == 1) {
				return false 
			} else {
				return true
			}
		},
		showKxxx () {
			if (this.model.lx  == 2) {
				return this.model.sfbgkxxx == '1'
			} else {
				return true
			}
		},
		// 控制框架合同的显隐
		showframeContract () {
			return this.model.isFrameContract && this.model.isFrameContract == 'yes'
		}
  },
  methods: {
		checkDisabled(key) {
		  const keyStrategy = {
				tdhskj: ['confirmIncomeMethod', 'rateList'], // 团队核算会计 - 收入确认方式，税率
				rdsh: ['distributionMethod', 'businessPerformance', 'classList'], // 入档审核 分配方式，经营绩效，任务信息列表，是否变更款项信息，收付款计划列表
				rdqr: ['distributionMethod', 'businessPerformance', 'classList'], // 入档审核 分配方式，经营绩效，任务信息列表，是否变更款项信息，收付款计划列表
				qrhtgd: [
					// 必填
					'htmc', 'jytd', 'yjgsnd', 'yzdw', 'qdrq', 'distributionMethod', 'ownerRole', 'contractChangeReason', 'masterCopy', 'sfcd', 'cdfs', 'contractFileType', 'bchte', 'fwqx', 'fwqxEnd', 'entrustList',
					'trusteeList', 'classList', 'sfbgkxxx', 'planList',
					// 非必填
					'lxr', 'lxfs', 'bz', 'yjxx', 'xgfj'
				],
				// xmzy: ['instruction', 'taskFile', 'approvalEngineer']
			}
		  const ignoreKeys = keyStrategy[this.extendUrlParams.node] || []
		  if (ignoreKeys.includes(key)) {
		    return false
		  }
		  return true
		},
		initRules() {
			const ruleStrategy = {
				tdhskj: {
					confirmIncomeMethod: [
						{ required: true, message: '请选择收入确认方式!' }
					]
				},
				rdsh: {
					distributionMethod: [
						{ required: true, message: '请选择分配方式!' }
					],
					businessPerformance: [
						{ required: true, message: '请输入经营绩效!' }
					],
				},
				rdqr: {
					distributionMethod: [
						{ required: true, message: '请选择分配方式!' }
					],
					businessPerformance: [
						{ required: true, message: '请输入经营绩效!' }
					],
				},
				qrhtgd: {
					qdrq: [
						{ required: true, message: '请选择签订日期!' }
					],
					sfcd: [
						{ required: true, message: '请选择是否存档!' }
					],
					cdfs: [
						{ required: true, message: '请输入合同存档份数!' }
					],
					contractFileType: [
						{ required: true, message: '请选择存档形式!' }
					],
				}
			}
			if (this.extendUrlParams && this.extendUrlParams.node) {
				const rules = ruleStrategy[this.extendUrlParams.node] || {}
				this.rules = Object.assign(this.rules, rules)
			}
		},
		checkRequired(key) {
		  return Object.keys(this.rules).includes(key) || false
		},
		// 选择下框架合同，关联框架合同置空
		handleChangeFrameContract () {
			this.$set(this.model, 'frameContractId', null);
			this.$refs.form.clearValidate('frameContractId'); // 切换清除校验
		},
		async initDictConfig() {
      initDictOptions('erp_company_files,file_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'gsda', res.result)
        }
      })
			initDictOptions('org_payment_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'contractPaymentType', res.result)
        }
      })
    },
    
		changeBusinessCompany(val){
      this.model.businessCompanyId = val.belongCompanyId
      },

		handleBorrowDateChange(date, dateStr) {
		  this.$set(this.model, 'fwqxEnd', undefined)
		  this.fwqxEnd = undefined
		},
		predictReturnDateChange (date, dateStr) {
			if (!this.model.fwqx) {
				return false
			}
			let isBefore = moment(this.model.fwqx).isBefore(this.model.fwqxEnd)
			if (!isBefore) {
				const format = 'YYYY-MM-DD'
				const fwqx = moment(this.model.fwqx, format)
				const fwqxEnd = moment(this.model.fwqxEnd, format)
				if (fwqx.isSame(fwqxEnd)) {
					return false
				}
				this.$refs.uToast.show({
					message:'服务期限结束时间必须大于开始时间!'
				})
				this.$nextTick(() => {
					this.model.fwqxEnd = null
				})
			}
		},
		handleRules(val){
			if(this.model.sfyz == '1'){
				this.$set(this.model,'noFormalContract','') // 置空无正式合同
				this.$set(this.rules,'yzlx',[{ required: true, message: '请选择印章类型!' }])
				this.$set(this.rules,'yyfs',[
          { required: true, message: '请输入用印份数!', trigger: 'blur' },
          { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
        ])
				this.$delete(this.rules,'masterCopy')
				this.$set(this.model,'masterCopy','')
			} else {
				this.$set(this.model,'noFormalContract','0') // 置空无正式合同
				this.$delete(this.rules,'yzlx')
				this.$delete(this.rules,'yyfs')
				this.$set(this.model,'yzlx','')
				this.$set(this.model,'yyfs','')
				this.$set(this.rules,'masterCopy',[{ required: true, message: '请上传合同原件!' }])
				this.$set(this.model, 'signSealWay', null) // 置空电子签章
			}
			this.$refs.form.clearValidate(['signSealWay', 'yzlx', 'yyfs', 'masterCopy', 'signFile']);
			if (val == 0) {
				if (this.formDataB && this.formDataB.length) {
					this.formDataB.forEach(value => {
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = '0'
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			}
		},
		// 点击选择用印类型
		handleSignSealWay (val) {
			if (val == 'online') {
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = '0'
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			} else {
				if (this.formDataB && this.formDataB.length) {
					this.formDataB.forEach(value => {
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = '0'
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			}
		},
		handleRules2(val){
			if(this.model.sfcd == '1'){
				// this.$set(this.rules,'cdfs',[
    //       { required: true, message: '请输入合同存档份数!', trigger: 'blur' }
    //     ])
			} else {
				// this.$delete(this.rules,'cdfs')
				this.$set(this.model,'cdfs',null)
				this.$set(this.model,'contractFileType',null)
			}
		},
		// 切换项目 任务信息  数据占比信息改变
		changeMoney(){
			if (this.model.bchte&&this.dataSource2.length) {
				this.dataSource2.forEach((item) => {
					if(this.model.distributionMethod==1){
						// 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
						// item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
						let amount = this.model.bchte * item.htzb / 100
						item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
					} else {
						// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
						let rate = item.fphte / this.model.bchte * 100
						item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
						// item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
					}
				})
			}
		},
    convertMoney2() {
      let money = this.model.bchte
      this.$set(this.model, 'bchtedx', convertCurrency(money))
      this.dataSource2.forEach((item, index) => {
				if(this.model.bchte>0){
					if(this.model.distributionMethod==1){
						// 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
						// item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
						let amount = this.model.bchte * item.htzb / 100
						item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
					} else {
						// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
						let rate = item.fphte / this.model.bchte * 100
						item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
						// item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
					}
				} else {
					if(this.model.distributionMethod==1){
						// 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
						item.fphte = 0
					} else {
						// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
						item.htzb = 0
					}
				}
				
      })
    },
		// 监听修改本次合同额数据
		convertMoneyBlur2 (item) {
			let money = Number(this.model.bchte)
			if (this.model.bchte) {
				this.$set(this.model, 'bchte', money.toFixed(2))
			}
		},
		// 选择项目名称
		xmmcInput (value) {
			this.$set(this.model, 'businessPerformance', value.businessPerformance || '') // 经营绩效
			this.$set(this.model, 'ownerRole', value.ownerRole || '') // 业主角色
			this.$set(this.model, 'mainProductionTeam', value.mainProductionTeam || '') // 主生产团队
			// 清空项目也清空带出来的定标结果确认单数据
			let val = value.id
			let data = value
			if (!val){
				this.model.calibrationId  = null
			}
			this.$set(this.model, 'yzdw', value.ownerUnit) // 业主单位
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
			this.$set(this.model, 'calibrationId', null) // 定标结果确认单
			// debugger;
			// this.model.lxdh = value.lxfs;
			this.$set(this.model, 'xmbh', value.finalNo) // 项目编号
			this.$set(this.model, 'jytd', value.oldTeamId?value.oldTeamId:value.teamName) // 经营团队
			this.$set(this.model, 'businessCompanyId', value.businessCompanyId) // 经营公司
			this.$set(this.model, 'yjgsnd', value.year) // 业绩归属年度
			this.$set(this.model, 'qddw', value.signUnit) // 签定单位
			this.$set(this.model, 'xmcjr', value.undertaker) // 项目承接人
			this.$set(this.model, 'lxfs', value.contactTel) // 联系方式
			this.$set(this.model, 'lxr', value.contacts) // 联系人
			this.$set(this.model,'distributionMethod',value.distributionMethod || '')
			this.projectName = value.projectName
			// 任务信息
			relationTaskList({ pageNo:1,pageSize: 999,projectId: value.id,distributionType: '!cancel' }).then((res) => {
			  this.dataSource2 = []
			  if (res.success) {
			    let data = res.result.records || res.result
			    for (let i = 0; i < data.length; i++) {
			      let d = {
			        id: data[i].id,
			        ywfl: data[i].categoryCode,
			        ywmc: data[i].categoryName,
			        htzb: data[i].contractRate,
			        fphte: data[i].contractAmount,
			        sctd: data[i].productTeam,
			        sctd_dictText: data[i].productTeam_dictText,
			        tdfzr: data[i].teamLeader,
			        tdfzr_dictText: data[i].teamLeader_dictText,
			        projectTaskId: data[i].id,
			        cutContractAmount: data[i].cutContractAmount,
			        productCompanyId: data[i].productCompanyId
			        // productCompanyId: data[i].productCompanyId ? filterMultiDictText(this.dictOptions['gsda'], data[i].productCompanyId + '') : ''
			      }
						this.dataSource2.push(d);
			      // let index = this.dataSource2.findIndex((item) => item.ywfl == d.ywfl)
			      // if (index > -1) {
			      //   this.dataSource2.splice(index, 1, d)
			      // } else {
			      //   this.dataSource2.push(d)
			      // }
			    }
					this.changeMoney()
			  }
			})
			this.bailChange(value.id)
		},
		// 选择合同编号
		htbhChange(val) {
			erpOmcContractManagerFinalQueryById({ id: val.id }).then((res) => {
				if (res.success) {
					let data = res.result.records || res.result
					// debugger;
					this.$set(this.model, 'yzdw', data.yzdw)// 业主单位
					this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
					this.$set(this.model, 'caId', val.id)
					this.$set(this.model, 'bpmBizTitle', data.htmc) // 标题
					this.$set(this.model, 'htmc', data.htmc) // 合同名称
					this.$set(this.model, 'htlx', data.htlx) // 合同类型
					this.$set(this.model, 'businessPerformance', data.businessPerformance) // 经营绩效
					// fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 start
					// fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 end
					this.$set(this.model, 'xmmc', data.xmmc) // 项目名称
					this.$set(this.model, 'jytd', data.jytd) // 经营团队
					this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
					this.$set(this.model, 'yjgsnd', data.yjgsnd)// 业绩归属年度
					this.$set(this.model, 'qddw', data.qddw) // 签订单位
					this.$set(this.model, 'xmcjr', data.xmcjr) // 项目承接人
					this.$set(this.model, 'lxr', data.lxr)// 联系人
					this.$set(this.model, 'lxfs', data.lxfs) // 联系方式
					this.$set(this.model, 'qdrq', data.qdrq)// 签订日期
					this.$set(this.model, 'sfyz', String(data.sfyz))// 是否用印
					this.$set(this.model, 'noFormalContract', data.noFormalContract || '')// 是否无正式合同
					this.$set(this.model, 'signSealWay', data.signSealWay)// 用印类型
					this.$set(this.model, 'signFile', data.signFile)// 用印文件
					if(data.sfyz == 1){
						this.$set(this.model, 'yzlx', data.yzlx) // 印章类型
						this.$set(this.model, 'yyfs', data.yyfs)// 用印份数
					} else {
						this.$set(this.model, 'yzlx', null) // 印章类型
						this.$set(this.model, 'yyfs', null)// 用印份数
						this.handleRules(this.model.sfyz)
					}
					this.$set(this.model, 'sfcd', data.sfcd)// 是否存档
					if(data.sfcd==1){
						this.$set(this.model, 'cdfs', data.cdfs)// 存档份数
						this.$set(this.model, 'contractFileType', data.contractFileType)// 存档形式
					} else {
						this.$set(this.model, 'cdfs', '')// 存档份数
						this.$set(this.model, 'contractFileType', '')// 存档形式
						this.handleRules2(this.model.sfcd)
					}
					this.$forceUpdate()
					this.$set(this.model, 'glskht', data.glskht) // 关联收款合同
					this.glhtFlag = data.glskht == '1'
					this.$set(this.model, 'skhtmc', data.skhtmc) // 收款合同名称
					// this.$set(this.model, 'jf', data.yzdw) // 甲方
					this.$set(this.model, 'jf', data.jf)// 甲方
					this.$set(this.model, 'yf', data.yf)// 已方
					// this.$set(this.model, 'yf', data.qddw) // 已方
					this.$set(this.model, 'skhte', data.skhte)// 收款合同额
					this.$set(this.model, 'skhtedx', data.skhtedx)// 收款合同额大写
					this.$set(this.model, 'businessPerformance', data.businessPerformance)// 经营绩效
					this.$set(this.model, 'feeType', data.feeType)// 费用类型
					this.$set(this.model, 'isFrameContract', data.isFrameContract)// 框架下合同
					this.$set(this.model, 'frameContractId', data.frameContractId)// 关联框架合同
					this.$set(this.model, 'ownerRole', data.ownerRole || null)// 业主角色
					this.$set(this.model, 'enterpriseType', data.enterpriseType || null)// 企业类型
					this.$set(this.model, 'mainProductionTeam', data.mainProductionTeam || null)// 主生产团队
					this.$set(this.model, 'confirmIncomeMethod', data.confirmIncomeMethod || null)// 收入确认方式
					this.$set(this.model, 'contractChangeReason', data.contractChangeReason || null)// 变更说明
					this.initTaxRateInfoList('edit', val.id, this.model.lx) // 获取合同税率
					let bchte = data.bchte;
					this.$set(this.model, 'bchte', bchte)
					this.$set(this.model, 'bchtedx', data.bchtedx)
					this.$set(this.model, 'fwqx', data.fwqx)
					this.$set(this.model, 'fwqxEnd', data.fwqxEnd)
					// 服务期限
					if (!!this.model.fwqx && !!this.model.fwqxEnd) {
						this.createTime = []
						this.createTime.push(this.model.fwqx)
						this.createTime.push(this.model.fwqxEnd)
					} else {
						this.createTime = []
					}
					this.$set(this.model, 'bz', data.bz) // 备注
					this.$set(this.model, 'yjxx', data.yjxx) // 邮寄信息
					this.$set(this.model, 'xgfj', data.xgfj) // 相关附件
					this.$set(this.model, 'htbh', data.htbh) // 合同编号
					this.$set(this.model, 'xmbh', data.xmbh) // 合同编号
			
					this.$set(this.model, 'isCategoryType', data.isCategoryType) // 是否采购类
					this.$set(this.model, 'provisionType', data.provisionType) // 采购类型
					this.$set(this.model, 'calibrationId', data.calibrationId) // 定标结果确认单
					this.$set(this.model, 'purchaseApplyId', data.purchaseApplyId) // 采购申请单
					// this.handleChangeCategory(data.isCategoryType)
					if (data.isCategoryType == '1') {
						this.handleChangeProvisionType(data.provisionType)
					}
					this.$set(this.model, 'bglx', data.bglx)
					if (this.model.bglx && this.model.bglx == '2') {
						this.$set(this.model, 'stopTime', data.stopTime || '')
					}
					this.$set(this.model, 'sfbgkxx', data.sfbgkxx)
					// this.$set(this.model, 'proposer', data.proposer)
					// this.$set(this.model, 'proposerDeptId', data.proposerDeptId)
					this.$set(this, 'isFkht', data.htlx != '1')
					this.$set(this.model, 'involveMultiple', data.involveMultiple)
					this.$set(this, 'involveMultipleFlag', data.involveMultiple == 1)
					if(this.model.sfyz == '1'){
						this.$delete(this.rules,'masterCopy')
					} else {
						this.$set(this.rules,'masterCopy',[{ required: true, message: '请上传合同原件!' }])
					}
					this.$set(this.model, 'masterCopy', data.masterCopy) // 合同原件
					this.$set(this.model, 'bail', '0.00')
					this.$set(this.model,'distributionMethod',data.distributionMethod || '')
					// 收款计划
					erpOmcContractManagerPlanFinalList({ mainId: val.id }).then((res) => {
						if (res.success) {
							// 为了老合同能变更，这里需判断收付款计划的款项类型是否包含了质保金和履约保证金，如果没有则需添加
							res.result = this.getInitDataSource(res.result)
							// res.result数组中的planTaskList数组中拼接categoryName形成款项关联任务
							res.result.map((value, index) => {
								res.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
								// 遍历planTaskList数组赋值给taskId_dictText
								res.result[index].taskId_dictText = value.planTaskList && value.planTaskList.length ? (value.planTaskList.map((obj, ind)=>{
									value.planTaskList[ind].finalId = obj.id
									return obj.categoryName
								}).join(",")):'';
							})
							this.formDataC = res.result.records || res.result
							if (this.formDataC.length > 0) {
								this.formDataC.forEach((item, index) => {
									item.finalId = item.id
								})
							}
						}
					})
					this.bailChange(val.xmmc) // 收付款计划获取最新的履约保证金
					// 任务信息
					listContractFinalTaskByProjectId( { projectId: data.xmmc }).then((res) => {
						let arr = res || []
						this.dataSource2 = []
						for (let i = 0; i < arr.length; i++) {
							let d = {
								id: arr[i].id,
								ywfl: arr[i].categoryCode,
								ywmc: arr[i].categoryName,
								htzb: arr[i].contractRate,
								fphte: arr[i].contractAmount,
								
								sctd: arr[i].productTeam,
								'shouldPayFlag': arr[i].shouldPayFlag, // 是否应收
								'distributionType': arr[i].distributionType, // 是否作废
								sctd_dictText: filterMultiDictText(this.dictOptions['sctd'], arr[i].productTeam + ''),
								tdfzr: arr[i].teamLeader,
								tdfzr_dictText: filterMultiDictText(this.dictOptions['tdfzr'], arr[i].teamLeader + ''),
								projectTaskId: arr[i].id,
								cutContractAmount: arr[i].cutContractAmount,
								productCompanyId: arr[i].productCompanyId
							}
							this.dataSource2.push(d);
						}
					}),
					// 项目赋值
					erpOmcProjectId( { id: data.xmmc }).then((res) => {
						if (res.success) {
							let data = res.result.records || res.result
							this.$set(this, 'projectName', data.projectName); // 项目名称
						}
					}),
					// 受托方信息
					erpOmcContractManagerTrusteeFinalList( { mainId: val.id }).then((res) => {
						if (res.success) {
							this.formDataB = res.result.records || res.result
							this.formDataB.forEach((item, index) => {
								item.finalId = item.id
							})
						}
					}),
					// 委托方信息
					erpOmcContractManagerEntrustFinalList( { mainId: val.id }).then((res) => {
						if (res.success) {
							this.formDataA = res.result.records || res.result
							this.formDataA.forEach((item, index) => {
								item.finalId = item.id
							})
						}
					})
						}
				})
		},
		// 接口获取收付款计划时当无质保金和履约保证金时，初始化数据
		getInitDataSource (arr) {
			// 为了老合同能变更，这里需判断收付款计划的款项类型是否包含了质保金和履约保证金，如果没有则需添加
			const index = arr.findIndex(item => item.contractPaymentType == 'bail');
			if (index == -1) {
				arr = [
					...arr,
					{
						id: parseInt(Math.random() * 1000000000000),
						contractPaymentType: 'bail', // 履约保证金类型
						contractPaymentType_dictText: '履约保证金', // 履约保证金类型
						kxmc: '履约保证金', // 款项名称
						je: null, // 金额
						planTaskList: [], // 任务信息
						collectMoneyStatus: '未生成', // 收款状态
						taskId_dictText: null // 款项关联任务
					},
					{
						id: parseInt(Math.random() * 1000000000000),
						contractPaymentType: 'quality', // 质保金类型
						contractPaymentType_dictText: '质保金', // 质保金类型
						kxmc: '质保金', // 款项名称
						je: null, // 金额
						kxrq: null, // 预计款项日期
						kxjdsm: null, // 款项节点说明
						planTaskList: [], // 任务信息
						collectMoneyStatus: '未生成', // 收款状态
						taskId_dictText: null // 款项关联任务
					}
				];
			}
			return arr
		},
		bailChange (id) {
			var params = {
			  preProjectId: id,
			  feeCategory: '2',
			  bpmStatus: '3',
			}
			// 查看项目保证金
			erpFinanceProjectDepositBillqueryByEntity(params).then((res) => {
			  if (res.success) {
					let data = res.result.records || res.result
					// 收付款计划履约保证金赋值
					this.formDataC.map((item) => {
						if (item.contractPaymentType == 'bail') {
							item.je = data.remittanceAmount
						}
					})
				} else {
					// 收付款计划履约保证金赋值
					this.formDataC.map((item) => {
						if (item.contractPaymentType == 'bail') {
							item.je = '0'
						}
					})
				}
			}).catch(err => {
        // 收付款计划履约保证金赋值
        this.formDataC.map((item) => {
          if (item.contractPaymentType == 'bail') {
            item.je = '0'
          }
        })
      })
		},
		// 选择业主单位
		yzdwChange (val) {
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
			this.$set(this.model, 'lxr', undefined);
			this.$set(this.model, 'lxfs', undefined);
			this.$set(this.model, 'enterpriseType', val.enterpriseType || '');
		},
		// 选择联系人
		lxrChange (val) {
			erpOmcCustomerManagerContactId({ id: val }).then((res) => {
				if (res.success) {
					let data = res.result.records || res.result
					this.$set(this.model, 'lxr', val)
					this.$set(this.model, 'lxfs', data.lxfs)
				}
			})
		},
    handleCopyFormA([item, index]) {
      this.formDataA.push({
        ...item,
      })
			this.$refs.uToast.show({
				message:'复制成功!'
			})
    },
    handleEditFormA([item, index]) {
      this.basicFormA = { ...item }
      this.index = index
      this.showFormModalA = true
			this.$nextTick(() => {
				this.openFormModalA()
			})
    },
    handleRemoveFormA(item) {
      this.formDataA = this.formDataA.filter((i) => i !== item)
    },
    closeFormModalA() {
      this.$refs.dataFormA.reset()
      this.basicFormA = {}
      this.index = null
			this.showFormModalA = false
    },
    openFormModalA() {
      this.$refs.dataFormA.basicForm = Object.assign({},this.basicFormA)
    },
    handleCopyFormB([item, index]) {
      this.formDataB.push({
        ...item,
      })
			this.$refs.uToast.show({
				message:'复制成功!'
			})
    },
    addFormA() {
      this.index = null
			this.basicFormA = {}
      this.showFormModalA = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitA([data, index]) {
      this.showFormModalA = false
      if (typeof index === 'number') {
        this.$set(this.formDataA, index, data)
      } else {
        this.formDataA.push(data)
      }
    },
    handleEditFormB([item, index]) {
      this.basicFormB = { ...item }
      this.index = index
      this.showFormModalB = true
			this.$nextTick(() => {
				this.openFormModalB()
			})
    },
    handleRemoveFormB(item) {
      this.formDataB = this.formDataB.filter((i) => i !== item)
    },
    closeFormModalB() {
      this.$refs.dataFormB.reset()
      this.basicFormB = {}
      this.index = null
			this.showFormModalB = false
    },
    openFormModalB() {
      this.$refs.dataFormB.basicForm = Object.assign({},this.basicFormB)
    },
    addFormB() {
      this.index = null
			this.basicFormB = {}
      this.showFormModalB = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitB([data, index]) {
      this.showFormModalB = false
      if (typeof index === 'number') {
        this.$set(this.formDataB, index, data)
      } else {
        this.formDataB.push(data)
      }
    },
    handleEditFormC([item, index]) {
      this.basicFormC = { ...item }
      this.index = index
      this.showFormModalC = true
			this.$nextTick(() => {
				this.openFormModalC()
			})
    },
		handleDetailFormC ([item, index]) {
      this.basicFormC = { ...item }
      this.index = index
      this.showFormModalC = true
			this.$nextTick(() => {
				this.openFormModalC()
			})
    },
    handleRemoveFormC(item) {
      this.formDataC = this.formDataC.filter((i) => i !== item)
			// 判断删除的款项类型是否为进度款
			if (item.contractPaymentType == 'progress') {
				// 筛选出款项类型为进度款的
				var index = 1
				this.formDataC.map(value => {
					if (value.contractPaymentType == 'progress') {
						value.kxmc = '进度款' + index;
						index++;
						return value
					}
				})
			}
    },
    closeFormModalC() {
      this.$refs.dataFormC.reset()
      this.basicFormC = {}
      this.index = null
			this.showFormModalC = false
    },
    openFormModalC() {
      this.$refs.dataFormC.basicForm = Object.assign({},this.basicFormC)
      this.$refs.dataFormC.defineBasicForm = Object.assign({},this.basicFormC)
      this.$refs.dataFormC.formDataC = this.basicFormC.planTaskList || []
    },
    handleCopyFormC([item, index]) {
      this.formDataC.push({
        ...item,
      })
      this.$refs.uToast.show({
      	message:'复制成功!'
      })
    },
    addFormC() {
      this.index = null
			this.basicFormC = {}
      this.showFormModalC = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitC([data, index]) {
      this.showFormModalC = false
      if (typeof index === 'number') {
        this.$set(this.formDataC, index, data)
				// 筛选出款项类型为进度款的
				var ind = 1
				this.formDataC.map(value => {
					if (value.contractPaymentType == 'progress') {
						value.kxmc = '进度款' + ind;
						ind++;
						return value
					}
				})
      } else {
				this.formDataC.push(data);
      }
			this.dataSourceSort()
    },
		// 收付款计划排序
		dataSourceSort() {
			// 新增收付款计划后，子表按款项类型（首付款、进度款、尾款、全款）—质保金—履约保证金排序
			// 同一款项类型下，按照款项1-N排序
			const contractPaymentType =  this.dictOptions.contractPaymentType;
			contractPaymentType.push({ text: '履约保证金', title: '履约保证金', value: 'bail' }, { text: '质保金', title: '质保金', value: 'quality' })
			this.formDataC.sort((item1, item2) => {
				// 获取 item1 和 item2 在数据字典中的索引
				const index1 = contractPaymentType.findIndex(dictItem => dictItem.value === item1.contractPaymentType);
				const index2 = contractPaymentType.findIndex(dictItem => dictItem.value === item2.contractPaymentType);
				// 根据索引比较大小
				return index1 - index2;
			});
		},
		handleEditFormRate([item, index]) {
		  this.basicFormRate = { ...item }
		  this.index = index
		  this.showFormModalRate = true
			this.$nextTick(() => {
				this.openFormModalRate()
			})
		},
		handleRemoveFormRate(item) {
		  this.formDataRate = this.formDataRate.filter((i) => i !== item)
		},
		closeFormModalRate() {
		  this.$refs.dataFormRate.reset()
		  this.basicFormRate = {}
		  this.index = null
			this.showFormModalRate = false
		},
		openFormModalRate() {
		  this.$refs.dataFormRate.basicForm = Object.assign({},this.basicFormRate)
		},
		handleCopyFormRate([item, index]) {
		  this.formDataRate.push({
		    ...item,
		  })
		  this.$refs.uToast.show({
		  	message:'复制成功!'
		  })
		},
		addFormRate() {
		  this.index = null
			this.basicFormRate = {}
		  this.showFormModalRate = true
		},
		/**
		 * 子表单新增点击确认
		 */
		handleFormSubmitRate([data, index]) {
		  this.showFormModalRate = false
		  if (typeof index === 'number') {
		    this.$set(this.formDataRate, index, data)
		  } else {
		    this.formDataRate.push(data)
		  }
		},
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'HT', subSystemCode: '05' })
      this.model.htbh = res.result
      // this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.htbh //标题
    },
    // 初始化新增需要的数据
    initForm(type) {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      if (type == '1') {
      	this.initPlanList('add') // 初始化收付款计划
      	this.initTaxRateInfoList('add') // 初始化合同税率
      } else {
      	this.initPlanList('add2') // 初始化收付款计划
      	this.initTaxRateInfoList('add2') // 初始化合同税率
      	this.$set(this.model, 'sfbgkxxx', '0') // 是否变更收付款计划默认为否
      	this.$set(this.model, 'caId', '') // 合同编号
      	this.$set(this.model, 'bglx', '') // 变更类型
      	this.$set(this.model, 'stopTime', '') // 终止时间
      }
    },
		// 初始化收付款计划
		initPlanList(type) {
			if (type == 'add') {
				this.formDataC = [
					{
						id: parseInt(Math.random() * 1000000000000),
						contractPaymentType: 'bail', // 履约保证金类型
						contractPaymentType_dictText: '履约保证金', // 履约保证金类型
						kxmc: '履约保证金', // 款项名称
						je: null, // 金额
						planTaskList: [], // 任务信息
						collectMoneyStatus: '未生成', // 收款状态
						taskId_dictText: null // 款项关联任务
					},
					{
						id: parseInt(Math.random() * 1000000000000),
						contractPaymentType: 'quality', // 质保金类型
						contractPaymentType_dictText: '质保金', // 质保金类型
						kxmc: '质保金', // 款项名称
						je: null, // 金额
						kxrq: null, // 预计款项日期
						kxjdsm: null, // 款项节点说明
						planTaskList: [], // 任务信息
						collectMoneyStatus: '未生成', // 收款状态
						taskId_dictText: null // 款项关联任务
					}
				]
			} else {
				this.formDataC = [] // 直接清空收付款计划
			}
		},
		// 初始化合同税率
		initTaxRateInfoList(type, id = '', typeLx='') {
			if (type == 'add') {
				// 税率
			initDictOptions('contract_rate_type').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'contractRateType', res.result)
					this.formDataRate = this.dictOptions.contractRateType.map((item, index) => {
						return {
							key: index,
							amount: 0, // 含税金额
							taxRate: item.value, // 税率
							taxRate_dictText: item.text, // 税率
							taxation: 0, // 税额
							untaxedAmount: 0, // 未税金额
						} 
					})
				} else {
					this.$refs.uToast.show({
						message: res.message
					})
				}
			})
			} else if (type == 'add2') {
				this.formDataRate = []
			}
			 else {
				this.formDataRate = [] // 清空
				let params = {
					contractId: id,
					pageNo: 1,
					pageSize: -1
				}
				var url = ''
				if (typeLx && typeLx == '2') {
					url = '/api/erp/omc/contractmanager/erpOmcContractRateFinal/list'
				} else {
					url = '/api/erp/omc/contractmanager/erpOmcContractRate/list'
				}
				http.get(url, params).then(res => {
					if (res.success) {
						this.formDataRate = res.result.records || res.result || []
						 // 当typeLx为2时，代表为变更，则需要把id重新赋值给finalId
						if (typeLx && typeLx == '2') {
							if (this.formDataRate && this.formDataRate.length > 0) {
								this.formDataRate.forEach((item, index) => {
									item.finalId = item.id
									item.key = index
								})
							}
						} else {
							this.formDataRate.forEach((item, index) => {
								item.key = index
							})
						}
						if (this.formDataRate.length === 0) {
							initDictOptions('contract_rate_type').then((res) => {
								if (res.success) {
									this.$set(this.dictOptions, 'contractRateType', res.result)
									this.formDataRate = this.dictOptions.contractRateType.map((item, index) => {
										return {
											key: index,
											amount: 0, // 含税金额
											taxRate: item.value, // 税率
											taxRate_dictText: item.text, // 税率
											taxation: 0, // 税额
											untaxedAmount: 0, // 未税金额
										} 
									})
								} else {
									this.$refs.uToast.show({
										message: res.message
									})
								}
							})
						}
					}
				})
			}
		},
    async loadData() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + data.yzdw + '\'';
			this.model = Object.assign({}, data)
			var title = this.model.lx  == '1'? '项目收款合同申请流程' : '项目收款合同变更流程'
			uni.setNavigationBarTitle({
				title: title
			})
			this.$set(this.model,'sfyz',(data.sfyz === null ||  data.sfyz === '' || data.sfyz === undefined)?'':String(data.sfyz))
			this.$set(this.model, 'bchtedx', convertCurrency(this.model.bchte))
			this.projectName = this.model.xmmc_dictText
			const resA = await erpOmcContractManagerEntrustListAll({ mainId: this.model.id })
			this.formDataA = resA.result.records || resA.result
			const resB = await erpOmcContractManagerTrusteeListAll({ mainId: this.model.id })
			this.formDataB = resB.result.records || resB.result
			this.initTaxRateInfoList('edit', this.model.id) // 初始化合同税率
			const resC = await erpOmcContractManagerPlanListAll({ mainId: this.model.id }) // 收付款计划
			// 为了老合同能变更，这里需判断收付款计划的款项类型是否包含了质保金和履约保证金，如果没有则需添加
			resC.result = await this.getInitDataSource(resC.result)
			// resC.result数组中的planTaskList数组中拼接categoryName形成款项关联任务
			resC.result.map((value, index) => {
				resC.result[index].taskId_dictText = '' // 首先款项关联任务字段默认为空
				// 遍历planTaskList数组赋值给taskId_dictText
				resC.result[index].taskId_dictText = value.planTaskList && value.planTaskList.length ? (value.planTaskList.map((obj)=>{return obj.categoryName }).join(",")):'';
			})
			this.formDataC = resC.result.records || resC.result
			const resData = await erpOmcContractManagerClassListAll({ mainId: this.model.id })
			this.dataSource2 = resData.result.records || resData.result
			this.dataSource2.forEach((item, index) => {
				if (this.model.bchte) {
					if (this.model.distributionMethod == 1) {
						// 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
						// item.fphte = parseFloat(item.htzb*0.01*parseFloat(this.model.bchte)).toFixed(2)
						let amount = this.model.bchte * item.htzb / 100
						item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100
					} else {
						// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
						let rate = item.fphte / this.model.bchte * 100
						item.htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
						// item.htzb = parseFloat(parseFloat(item.fphte) / parseFloat(this.model.bchte)*100).toFixed(2)
					}
				} else {
					if (this.model.distributionMethod == 1) {
						// 按比例：更改预计合同额，占比不变、对应的分配合同额实时变化
						item.fphte = 0
					} else {
						// 按金额：更改预计合同额，分配合同额不变、对应的占比实时变化
						item.htzb = 0
					}
				}
			})
			this.handleRules()
			this.handleRules2()
    },
    valdateContractMoney() {
			// 判断收付款计划款项类型是否为空的
			let planType = this.formDataC.some(item => !item.contractPaymentType);
			if (planType) {
				this.$refs.uToast.show({
					message:'收付款计划中“款项类型”未填写，请重新填写!'
				})
				return false
			}
      let planSum = 0
      this.formDataC.forEach((data) => {
				if (data.contractPaymentType != 'bail') {
					planSum += parseFloat(data.je || 0);
				}
      })
      // 迭代11 TASK#3763 2.收付款计划栏金额与合同总金额不对等时不可以发起，需要校验核对收付款计划金额和合同总金额
      if (Number(this.model.bchte).toFixed(2) != planSum.toFixed(2)) {
				this.$refs.uToast.show({
					message:'收付款计划中“金额”之和不等于“本次合同额”，请重新填写!'
				})
        return false
      }
      // 付款合同的本次合同额应该只是对外的任务的金额，不能校验本次合同额等于所有任务的总额
      if (this.model.htlx === 1 || this.model.htlx === '1') {
				if(this.model.distributionMethod==1){
					let rate = 0
					this.dataSource2.forEach(val => {
						rate += parseFloat(val.htzb)
					})
					if (rate != 100) {
						this.$refs.uToast.show({
							message:'任务信息中“合同占比”之和不等于100%，请重新填写!'
						})
						return false;
					}
				} else {
					let total = 0
					this.dataSource2.forEach((val) => {
					  total += parseFloat(val.fphte)
					})
					if (total.toFixed(2) != parseFloat(this.model.bchte).toFixed(2)) {
						this.$refs.uToast.show({
							message:'任务信息中“分配合同额”之和不等于“本次合同额”，请重新填写!'
						})
					  return false
					}
				}
      }
			// 判断税率中的含税金额之和等于本次合同额
			const contractTaxRatedataSource = this.formDataRate || []
			// 计算含税金额之和
			let rateSum = contractTaxRatedataSource.reduce((total, item) => {
				return total + Number(item.amount || 0)
			}, 0)
			if (rateSum.toFixed(2) != parseFloat(this.model.bchte).toFixed(2)) {
				this.$refs.uToast.show({
					message:'合同税率中“含税金额”之和不等于“本次合同额”，请重新填写!'
				})
				return false
			}
      return true
    },
    // 校验委托方和受托方子表数据合法性 委托方和受托方列表需要校验两个分别必须至少有一条数据 是否为收付款单位有各且仅有一个
    validateClientDetailAndTrusteeDetail() {
      if (!this.formDataA.length) {
				this.$refs.uToast.show({
					message:'请填写委托方信息!'
				})
        return false
      }
      if (!this.formDataB.length) {
				this.$refs.uToast.show({
					message:'请填写受托方信息!'
				})
        return false
      }
      const hasFkList = this.formDataA.filter((i) => i.isFk === '1')
    //   if (hasFkList.length !== 1) {
    //     this.$refs.uToast.show({
				// 	message:'委托方有且仅有一个是付款单位!'
				// })
    //     return false
    //   }
			if (hasFkList.length <= 0) {
			  this.$refs.uToast.show({
					message:'委托方必须有一个是付款单位!'
				})
			  return false
			}
			
			// 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
			// let psnName = this.formDataA.filter(item => item.psnName);
			// let psnMobile = this.formDataA.filter(item => item.psnMobile);
			if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
				// 当主表选择了电子签章
				for (var i = 0; i < this.formDataA.length; i++) {
					if (this.formDataA[i].isSignSeal && this.formDataA[i].isSignSeal == 1) {
						if (!this.formDataA[i].psnName || !this.formDataA[i].psnMobile) {
							this.$refs.uToast.show({
								message:'请填写委托方联系人和联系方式!'
							})
							return
						}
					}
				}
			}
      const hasSkList = this.formDataB.filter((i) => i.isSk === '1')
      if (hasSkList.length !== 1) {
				this.$refs.uToast.show({
					message:'受托方有且仅有一个是收款单位!'
				})
        return false
      }
			// 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
			let psnName = this.formDataB.filter(item => !item.psnName);
			let psnMobile = this.formDataB.filter(item => !item.psnMobile);
			if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
				// 当主表选择了电子签章
				if (psnName.length || psnMobile.length) {
					this.$refs.uToast.show({
						message:'请填写受托方联系人和联系方式!'
					})
				return false;
				}
			}
      return true
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
				// 任务信息
        if (!this.valdateContractMoney()) {
          return Promise.reject('金额校验失败')
        }
				// 委托方受托方
        if (!this.validateClientDetailAndTrusteeDetail()) {
          return Promise.reject('信息校验失败')
        }
				// 收付款计划和含税列表数据
				if (!this.handleJudgePayment()) {
					return Promise.reject('收付款计划信息校验失败')
				}
        return Promise.resolve()
      })
    },
		// 判断需分配款项信息中的数据是否达到100%，如果达到则提交，否则提示需分配款项信息中的数据未达到100%
		handleJudgePayment() {
			var isTrue = true // true为通过，false为不通过
			// var _this = this
			var text = ''
			if (this.formDataC && this.formDataC.length > 0) {
				this.formDataC.forEach((item, index) => {
					// 判断当收付款计划中未达到应收状态时
					// 当collectMoneyStatus为未生成时，需要去除履约保证金的判断，因为履约保证金在未生成时，不参与判断
					if (item.collectMoneyStatus != '已生成' && item.contractPaymentType!= 'bail') {
						// 判断是否填写金额
						if (item.je=== null || item.je=== undefined || item.je === '') {
							text = `收付款计划中，款项名称为“${item.kxmc}”金额未填写!`
								isTrue = false
						}
						// 在判断金额是否等于0 等于0 的情况下是不需要绑定任务的，所以不需要判断
						if (Number(item.je) !== 0) {
							if (item && item.planTaskList && item.planTaskList.length > 0) {
								// 判断item1中的 paymentRate之和是否等于100%
								// const listTotal = item.planTaskList.reduce((total, item1) => {
								//   const paymentRate = Number(item1.paymentRate) || 0;
								//   const decimalContractRate = new Decimal(paymentRate);
								//   return total.plus(decimalContractRate);
								// }, new Decimal(0)).toNumber(); // 解决浮点数导致两者不相等
								// if (listTotal != 100) {
								//   text = '收付款计划中，“款项关联任务”中“款项分配占比”没有达到100%！，请重新填写!'
								//   isTrue = false
								// }
							} else {
								text = '收付款计划中，“款项关联任务”未绑定任务，需绑定任务!'
								isTrue = false // 没有任务时，不允许通过
							}
						}
					}
				})
			} else {
				text = '请填写“收付款计划”！'
				isTrue = false
			}
			if (!isTrue) {
				this.$refs.uToast.show({
					message:text
				})
			}
			return isTrue
		},
	//处理首付款计划，新增sortOrder字段
		handelPlanList(list){
			for (let i = 0; i < list.length; i++) {
				list[i].sortOrder=i;
			}
			return list;
		},
		
		// 查询流程流转信息 -- 获取下一节点信息
		getProcessTaskTrans(taskId){
			getProcessTaskTransInfo({ taskId }).then(res => {
				if(res.success){
					this.resultObj = res.result
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			}).catch(err => {
				console.log(err);
			})
		},
    async onSubmit() {
			var _this = this
			const hasNullCutContractAmount = this.dataSource2.some(item => item.cutContractAmount === '')
			if(hasNullCutContractAmount) return  this.$refs.uToast.show({message: '请填写切割合同额' }) 
      await this.validateForm()
			let url = ''
			if (this.id) {
				url = await edit
			} else {
				url = await add
			}
      try {
        const response = await url({
          ...this.model,
          entrustList: this.formDataA,
          trusteeList: this.formDataB,
          planList: this.handelPlanList(this.formDataC),
          classList: this.dataSource2,
					rateList: this.formDataRate || []
        })
				if (response.success) {
					this.$refs.uToast.show({
						message: '提交成功',
						type: 'success',
						complete () {
							_this.onAudit()
						}
					})
				  this.isSubmit = true
				} else {
					this.$refs.uToast.show({
						message: response.message,
						type: 'error'
					})
				}
      }  finally {
	    // this.loading = false
	  }
    },
    onAudit() {
      if (!this.isSubmit) {
        uni.showToast({
          title: '请完善表单后审核',
          icon: 'none',
        })
        return false
      }
      var that = this
      uni.navigateTo({
        url: '/pages/synergy/erpOmcContractManagerList' + `?item=${encodeURIComponent(JSON.stringify(that.processModel).replace(/%/g, '%25'))}`,
        success: function (data) {
          // 通过eventChannel向被打开页面传送数据
          var params = {
            nodeObj: that.dataNodeObj,
            tabvalue: that.tabvalue,
          }
          data.eventChannel.emit('sendMessage', params)
        },
        fail: function (err) {
          this.$refs.uToast.show({
            message: '请联系管理员配置',
            type: 'error',
          })
        },
      })
    },
  }
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
